package com.movie.listener;

import com.api.cinema.CinemaClients;
import com.movie.entity.Cinema;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;

import java.io.FileWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author xsl
 * @Date 2021/4/16 16:58
 * @Version 1.0
 **/
@Component
@RocketMQMessageListener(consumerGroup = "mh-cinema-consumer",
        topic = "cinema-2-page", selectorExpression = "cinema-2-page-tag",
        consumeMode = ConsumeMode.CONCURRENTLY,
        messageModel = MessageModel.CLUSTERING)
public class ConsumerListener implements RocketMQListener<Integer> {

    @Autowired
    private FreeMarkerConfig freeMarkerConfig;

    @Autowired
    private CinemaClients cinemaClients;

    @Value("${html.sink}")
    protected String SINK;

    @Override
    public void onMessage(Integer cinema_id) {
        System.out.println("cinema_id:" + cinema_id);

        //生成静态化页面
        genHTML(cinema_id);
    }

    private void genHTML(Integer cinema_id) {
        try {

            //生成静态化页面
            Configuration configuration = freeMarkerConfig.getConfiguration();
            Template template = configuration.getTemplate("cinema_detail.ftl");
            //远程调用获取影院详情
            List<Cinema> cinemaDetail = cinemaClients.findCinemaDetail(cinema_id);
            System.out.println(cinemaDetail);
            Map data = new HashMap();
            data.put("cinemaDetail", cinemaDetail);

            //创建输出流(Writer)对象
            Writer out = new FileWriter(SINK + "/" + cinema_id + ".html");
            //输出
            template.process(data, out);
            //关闭
            out.close();


        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
